using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public static class ArtGenRecordUtil
    {
        public class GenRecord
        {
            public Dictionary<string, HashSet<string>> entityDir_AnimClips = new();
        }

        private const string RecordPath = "/EditorConfig/ArtToolConfig/GenRecord.json";
        public static readonly string recordFullPath = Application.dataPath + RecordPath;

        private static GenRecord _record;

        public static void Record(string entityDir, AnimatorGenConfigAsset genAnimatorConfig)
        {
            _record = GetRecord();
            FillAnimClips(_record, entityDir, genAnimatorConfig.AniamtionPath);
            string json = JsonHelper.SerializeObject(_record);
            File.WriteAllText(recordFullPath, json);
        }

        private static void FillAnimClips(GenRecord record, string entityDir, string animDir)
        {
            if (!record.entityDir_AnimClips.TryGetValue(entityDir, out var clipNames))
            {
                clipNames = new();
                record.entityDir_AnimClips.Add(entityDir, clipNames);
            }
            clipNames.Clear();

            var animAssetPath = Path.Combine(entityDir, animDir);
            string[] guids = AssetDatabase.FindAssets("t:model", new string[] { animAssetPath });
            foreach (var guid in guids)
            {
                var p = AssetDatabase.GUIDToAssetPath(guid);
                var name = Path.GetFileNameWithoutExtension(p);
                clipNames.Add(name);
            }
        }

        public static GenRecord GetRecord()
        {
            if (_record == null)
            {
                if (!File.Exists(recordFullPath))
                {
                    _record = new GenRecord();
                    return _record;
                }
                var json = File.ReadAllText(recordFullPath);
                var rec = JsonHelper.DeserializeJson<GenRecord>(json);
                _record = rec;
                return _record;
            }
            return _record;
        }
    }
}
